package com.yulebaby.callsenter.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.orhanobut.logger.Logger;
import com.yulebaby.callsenter.R;
import com.yulebaby.callsenter.adapter.MultipleGoSeaAdapter;
import com.yulebaby.callsenter.bean.CustomerBean;
import com.yulebaby.callsenter.bean.multiplebean.MultipleCustomerBean;
import com.yulebaby.callsenter.global.Constant;
import com.yulebaby.callsenter.http.callback.ResultCallback;
import com.yulebaby.callsenter.task.CustomerDataConformTask;
import com.yulebaby.callsenter.task.RequestCustomerTask;
import com.yulebaby.callsenter.ui.activity.AddPreSaleRemarkActivity;
import com.yulebaby.callsenter.ui.activity.CustomerInfoActivity;
import com.yulebaby.callsenter.ui.base.BaseRecycleViewFragment;
import com.yulebaby.callsenter.ui.view.CallDialog;
import com.yulebaby.callsenter.ui.view.CustomPopwindow;
import com.yulebaby.callsenter.utils.PhoneUtil;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Nullable;

/**
 * Author: Zhangbo
 * Time: 2016/12/6
 */
public class ToSeaSoonFragment extends BaseRecycleViewFragment<List<CustomerBean>, MultipleGoSeaAdapter> {

    public ArrayList<MultipleCustomerBean> mMultipleCustomerList = new ArrayList<>();
    private MultipleGoSeaAdapter mAdapter = new MultipleGoSeaAdapter(mMultipleCustomerList);
    public ArrayList<String> phoneNumList = new ArrayList<>();
    private MultipleCustomerBean mCustomerBean;
    private CallDialog mCallDialog;

    private CustomPopwindow mCustomPopwindow;
    private int clickPosition = -1;

    public static ToSeaSoonFragment newInstance() {
        Bundle args = new Bundle();
        ToSeaSoonFragment fragment = new ToSeaSoonFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void requestData() {
        RequestCustomerTask.doGoSeaCustomer(mActivity, false, new ResultCallback<List<CustomerBean>>() {
            @Override
            public void onResult(List<CustomerBean> result) {
                processResult(result);
            }
        });
    }


    /**
     * 处理结果
     *
     * @param result
     */
    private void processResult(List<CustomerBean> result) {
        if (result != null) {
            mMultipleCustomerList.clear();
            if (result.size() > 0) {
                List<MultipleCustomerBean> beanList = CustomerDataConformTask.doGoSeaDataConform(result);
                mMultipleCustomerList.addAll(beanList);
            } else {
//                ToastUtil.showToast("您没有即将投公海的客户!");
            }
            mStateViewLayout.showSuccessView();
            mAdapter.notifyDataSetChanged();
            if (isRefreshing()) {
                refreshComplete();
            }
        } else {
            mStateViewLayout.showErrorView();
        }
    }


    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        requestData();
        mRecyclerView.addOnItemTouchListener(new OnItemClickListener() {

            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                int itemType = ((MultipleCustomerBean) adapter.getItem(position)).getItemType();
                if (itemType == MultipleCustomerBean.CUSTOMERITEM) {
                    //使用Intent的方式  使用消息总线的方式改进  粗糙版本
                    Intent intent = new Intent(mActivity, CustomerInfoActivity.class);
                    intent.putExtra(Constant.CUSTOMER_BEAN, ((MultipleCustomerBean) adapter.getItem(position)).getCustomerBean());
                    clickPosition = position;
                    intent.putExtra(Constant.IS_MODIFY, true);
                    startActivityForResult(intent, REQUEST_LOOKOVER_INFO);
                }
            }

            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                mCustomerBean = (MultipleCustomerBean) baseQuickAdapter.getItem(position);

                switch (view.getId()) {
                    case R.id.iv_robcustomer:
                        Logger.d("拨号");
                        //选择前清空一下集合
                        phoneNumList.clear();
                        checkHasPhoneNum(mCustomerBean.getCustomerBean());
                        switchCallNum();

                        break;
                    case R.id.tv_addtrack://添加售前跟踪
                        Logger.d("添加售前跟踪");
                        Intent addintent = new Intent(mActivity, AddPreSaleRemarkActivity.class);
                        addintent.putExtra(Constant.CUSTOMER_BEAN, mCustomerBean.getCustomerBean());
                        startActivity(addintent);
                        break;

                    case R.id.tv_looktrack://查看跟踪记录
                        if (mCustomerBean.getCustomerBean() != null) {
                            initCustomPopwindow(view);
                        }
                        break;
                }
            }
        });
        mRecyclerView.setAdapter(mAdapter);
    }


    /**
     * 初始化Popwindow
     *
     * @param view
     */
    private void initCustomPopwindow(View view) {
        mCustomPopwindow = new CustomPopwindow(mActivity, itemsOnClick, mCustomerBean.getCustomerBean());
        mCustomPopwindow.showAtLocation(view,
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    //为弹出窗口内部实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {

        public void onClick(View v) {
            mCustomPopwindow.backgroundAlpha(mActivity, 1f);
            switch (v.getId()) {
                case R.id.ib_cancal:
                    if (mCustomPopwindow != null && mCustomPopwindow.isShowing()) {
                        mCustomPopwindow.dismiss();
                    }
                    break;
                default:
                    break;
            }
        }

    };


    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(Activity context, float bgAlpha) {
        WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        context.getWindow().setAttributes(lp);
    }


    /**
     * 选择想要拨打的电话号码
     */
    private void switchCallNum() {
        if (phoneNumList.size() == 1) {
            PhoneUtil.callPhones(phoneNumList.get(0));
        } else {
            mCallDialog = new CallDialog(mActivity, phoneNumList, mCustomerBean.getCustomerBean());
            mCallDialog.setNumListener(new CallDialog.selectNumListener() {
                @Override
                public void selectNum(String num) {
                    PhoneUtil.callPhones(num);
//                    mCustomerBean.setRecent_call(1);
//                    Dao.getInstance().updateBean(mCustomerBean);
                }
            });
            mCallDialog.show();
        }
    }

    /**
     * 检查是否包含备用号码
     *
     * @param customerBean
     */
    private void checkHasPhoneNum(CustomerBean customerBean) {
        String phone = customerBean.getPhone();
        String spare_phone1 = customerBean.getSpare_phone1();
        String spare_phone2 = customerBean.getSpare_phone2();
        phoneNumList.add(phone);

        if (!TextUtils.isEmpty(spare_phone1)) {
            phoneNumList.add(spare_phone1);
        }

        if (!TextUtils.isEmpty(spare_phone2)) {
            phoneNumList.add(spare_phone2);
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mCustomPopwindow != null && mCustomPopwindow.isShowing()) {
            mCustomPopwindow.dismiss();
        }
    }

    /**
     * 有点问题 以后封装处理 TODO
     *
     * @param result
     * @return
     */
    @Override
    protected MultipleGoSeaAdapter getRecycleAdapt(List<CustomerBean> result) {
        return null;
    }
}
